package com.tim.third.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FetchRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * <dependency> <groupId>com.qiniu</groupId> <artifactId>qiniu-java-sdk</artifactId>
 * <version>7.11.0</version> </dependency>
 */
public class QiNiuFileDemo {
    private String accessKey="oDrfnQmj8IsQylnDJ-3_DytHb-TaCaPbLhkoOvSj";
    private String secretKey="FUGuXCeX9SVGQR90l2BZt6FtwCKEZUOfh5-oGewh";
    private String zone0="0";//存储区域华东
    private String bucketAvatar="xqxc-test-avatar";//存储域 公共存储域
    private String domainOfBucketImg="http://testavatar.xingqiuxiuchang.cn/";//存储域 公共存储域
    private final static String RETURN_BODY = "returnBody";

    Auth auth;
    BucketManager bucketManager;

    public static void main(String[] args) throws Exception {
        QiNiuFileDemo qiNiuFileService = new QiNiuFileDemo();
    /* step，文件转存到七牛*/
    //        String url =
    // "https://img-blog.csdnimg.cn/img_convert/f0208627800d66cb09ebe2fbf4ecaf7c.png" +
    //                "";
    //        String fileName = url.substring(url.lastIndexOf("/")+1).trim();
    //        String imgUrl = qiNiuFileService.fileUrlUpload(url, fileName);
    //        System.out.println(imgUrl);

    /* step，文件上传到七牛*/
    String url = "L:\\BaiduNetdiskWorkspace\\项目文件\\202305\\deliveryOrderExportTemplate.xlsx" +
            "";
        String temp = url.replaceAll("\\\\", "/");
        int index1 = temp.lastIndexOf("/");
        String fileName = temp.substring(index1 +1).trim();
        int index2 = fileName.lastIndexOf('.');
        FileInputStream fis = new FileInputStream(url);
        String imgUrl = qiNiuFileService.uploadFileWithStream(fis, fileName.substring(0, index2)+"_"+System.currentTimeMillis(), fileName.substring(index2));
        System.out.println(imgUrl);


    }

    public String uploadFileWithStream(InputStream is, String fileName, String suffix) {
        if (null == is) {return null;}
        UploadManager uploadManager = this.zoneUploadManager(this.zone0);
        StringBuffer sb = new StringBuffer();
        String key = StringUtils.isNotBlank(fileName)
                ? fileName
                : RandomStringUtils.randomAlphanumeric(32);
        try {
            Response put = uploadManager.put(is, sb.append(key).append(suffix).toString(), this.getPublicToken(), null, null);
            return this.getUrlPathPublic(put);
        }catch (QiniuException e){
            e.printStackTrace();
            throw new RuntimeException();
        }finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException();
            }
        }
    }

    private String getUrlPathPublic(Response response) {
        if (!response.isOK()) {
            return null;
        }
        DefaultPutRet defaultPutRet;
        try {
            defaultPutRet = response.jsonToObject(DefaultPutRet.class);
        } catch (QiniuException e) {
            e.printStackTrace();
            return null;
        }
        String key = defaultPutRet.key;
        return StringUtils.isNotBlank(key) ? domainOfBucketImg+key : null;
    }

    public String fileUrlUpload(String url, String fileName) {
        BucketManager manager = getUploadManager(zone0);
        FetchRet fetchRet = null;
        try {
            //调用fetch方法抓取文件
            fetchRet = manager.fetch(url, bucketAvatar, fileName);
            String imgUrl = fetchRet != null && StringUtils.isNotEmpty(fetchRet.key) ? domainOfBucketImg+fetchRet.key : "";
            return imgUrl;
        } catch (QiniuException e) {
            //捕获异常信息
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    private UploadManager zoneUploadManager(String zone) {
        Zone z = getZone(zone);
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(z);
        cfg.useHttpsDomains = false;
        return new UploadManager(cfg);
    }

    public String getPublicToken() {
        Auth auth = Auth.create(accessKey, secretKey);
//        return auth.uploadToken(bucketAvatar, fileName, 3600L, new StringMap().put(RETURN_BODY, policy()).put(MIMELIMIT, RESTRICTION_TYPE), true);
        return auth.uploadToken(bucketAvatar, null, 3600L, new StringMap().put(RETURN_BODY, policy()), true);
    }
    private String policy() {
        Map<String, Object> returnBody = new HashMap<>();
        returnBody.put("key", "$(key)");
        returnBody.put("size", "$(fsize)");
        returnBody.put("hash", "$(etag)");
        returnBody.put("type", "$(mimeType)");
        returnBody.put("w", "$(imageInfo.width)");
        returnBody.put("h", "$(imageInfo.height)");
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(returnBody));
        return jsonObject.toJSONString();
    }

    private BucketManager getUploadManager(String zone) {
        Zone z = getZone(zone);// z 为 null
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(z);
//        Auth auth = Auth.create(accessKey, secretKey);
        if(bucketManager == null){
            bucketManager  = new BucketManager(getInstance(), cfg);
        }
        return this.bucketManager;
    }

    private Auth getInstance() {
        if (null == auth) {
            auth =  Auth.create(accessKey, secretKey);
        }
        return this.auth;
    }


    protected final static String EAST_CHINA = "0";//华东

    protected final static String NORTH_CHINA = "1";//华北

    protected final static String SOUTH_CHINA = "2";//华南

    protected final static String NORTH_AMERICA = "Na0";//北美

    protected final static String SOUTHEAST_ASIA = "As0";//东南亚


    /**
     * @Description: 可以通过该方法获取七牛 区域对象
     * @Param:
     * @return:
     * @Author: CXiaoLin
     * @Date:
     */
    public static Zone getZone(String code) {
        switch (code) {
            case EAST_CHINA:
                return Zone.zone0();
            case NORTH_CHINA:
                return Zone.zone1();
            case SOUTH_CHINA:
                return Zone.zone2();
            case NORTH_AMERICA:
                return Zone.zoneNa0();
            case SOUTHEAST_ASIA:
                return Zone.zoneAs0();
            default:
                return null;
        }
    }
}
